package com.platform.common.utils.mch;

import com.alibaba.fastjson.JSONObject;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.RestResponse;
import com.platform.common.utils.mch.config.MchConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.Optional;

@Slf4j
public class HttpUtils {

    private final static CloseableHttpClient HTTP_CLIENT = HttpClients.createDefault();

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url    发送请求的 URL
     * @param body 请求的参数
     * @return 远程资源的响应结果
     */
    public static JSONObject sendPost(String url, String body) {
        log.debug("请求地址： {}", url);
        log.debug("请求参数： {}", body);
        HttpPost httpPost = new HttpPost(url);
        try {
            // 加密通信
            body = CodecUtil.dataEncode(body, MchConfig.getSystemCode()).toJSONString();
            httpPost.setEntity(new StringEntity(body));
            httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
            CloseableHttpResponse response = HTTP_CLIENT.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            log.debug("返回值： {}",result);
            RestResponse restResponse = JSONObject.parseObject(result, RestResponse.class);
            response.close();
            if (!"0".equals(Optional.ofNullable(restResponse.get("code")).map(Object::toString).orElseThrow(() -> new BusinessException("错误的返回值！")))) {
                throw new BusinessException(restResponse.get("msg").toString());
            }
            return (JSONObject)restResponse.get("data");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url    发送请求的 URL
     * @param params 请求的参数集合
     * @return 远程资源的响应结果
     */
    public static JSONObject sendPost(String url, JSONObject params) {
        return sendPost(url, params.toJSONString());
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url    发送请求的 URL
     * @param params 请求的参数
     * @param tClass 返回类型
     * @return 远程资源的响应结果
     */
    public static <T> T sendPost(String url, String params, Class<T> tClass) {
        JSONObject responseContent = sendPost(url, params);
        if(responseContent == null){
            return null;
        }
        T result;
        try {
            result = responseContent.toJavaObject(tClass);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url    发送请求的 URL
     * @param params 请求的参数集合
     * @param tClass 返回类型
     * @return 远程资源的响应结果
     */
    public static <T> T sendPost(String url, JSONObject params, Class<T> tClass) {
        return sendPost(url, params.toJSONString(), tClass);
    }

}
